package org.restly.core;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Jan 19, 2008, 7:16:21 PM
 *
 * @author <a href="http://restly.org/">Erik Beeson</a>
 */
public class FileLocator {

	public static String[] getFilenames(String filename) {
		File root = new File(Thread.currentThread().getContextClassLoader().getResource("/").getFile());

		List<String> filenames = getFilenames(root, filename, root.getAbsolutePath().length()+1);

		return filenames.toArray(new String[filenames.size()]);
	}

	private static List<String> getFilenames(File directory, String filename, int prefix) {
		List<String> filenames = new ArrayList<String>();

		for(File file : directory.listFiles()) {
			if(file.isDirectory()) {
				filenames.addAll(getFilenames(file, filename, prefix));
			} else if(file.isFile() && file.getName().equals(filename)) {
				filenames.add(file.getAbsolutePath().substring(prefix));
			}
		}

		return filenames;
	}

	public static Class[] getClasses() {
		return getClassesFromPackage("", true);
	}

	public static Class[] getClassesFromPackage(String packageName) {
		return getClassesFromPackage(packageName, false);
	}

	public static Class[] getClassesFromPackage(String packageName, boolean recursive) {
		List<Class> classes = new ArrayList<Class>();

		File directory = null;
		try {
			directory = new File(Thread.currentThread().getContextClassLoader().getResource('/' + packageName.replace('.', '/')).getFile());
		} catch(NullPointerException e) {
		}

		if(directory != null && directory.isDirectory()) {
			if(recursive) {
				getClassesFromDir(packageName, directory, classes);
			} else {
				for(String file : directory.list()) {
					if(file.endsWith(".class")) {
						try {
							classes.add(Class.forName(packageName + '.' + file.substring(0, file.length() - 6)));
						} catch(ClassNotFoundException e) {
						}
					}
				}
			}
		}

		return classes.toArray(new Class[classes.size()]);
	}

	private static void getClassesFromDir(String packageName, File directory, List<Class> classes) {
		for(File file : directory.listFiles()) {
			String fileName = file.getName();
			if(file.isDirectory()) {
				getClassesFromDir(getPackageName(packageName) + fileName, file, classes);
			} else if(fileName.endsWith(".class")) {
				try {
					classes.add(Class.forName(getPackageName(packageName) + fileName.substring(0, fileName.length() - 6)));
				} catch(ClassNotFoundException e) {
				}
			}
		}
	}

	private static String getPackageName(String s) {
		return s.length() > 0 ? (s + ".") : "";
	}
}